package com.gitee.apanlh.util.net.http.handler.body;

import com.gitee.apanlh.exp.HttpBodyParseException;
import com.gitee.apanlh.util.base.Eq;
import com.gitee.apanlh.util.base.IteratorUtils;
import com.gitee.apanlh.util.encode.StrEncodeUtils;
import com.gitee.apanlh.util.net.http.HttpBody;
import com.gitee.apanlh.util.net.http.HttpClient;
import com.gitee.apanlh.util.net.http.HttpRequest;
import com.gitee.apanlh.util.net.http.HttpUrl;
import com.gitee.apanlh.util.valid.ValidParam;

import java.util.Map;

/**
 * 	HTTPBody请求体解析
 * 	<br>RESTful风格请求，仅支持URL
 * 	<br>将改变URL参数
 * 
 * 	@author Pan
 */
public class HttpBodyPathVariableParseStrategy implements HttpBodyParseStrategy {

	@Override
	public HttpRequest parse(HttpRequest httpRequest, HttpClient httpClient) throws HttpBodyParseException {
		return toPathVariable(httpRequest);
	}

    /**
     * 	将对象转化转换RSETful风格
     * 	<br>顺序添加节点
     * 	
     * 	@author Pan
     * 	@param 	httpRequest	HTTP请求对象
     * 	@return	HttpRequest
     */
	HttpRequest toPathVariable(HttpRequest httpRequest) {
		HttpUrl url = httpRequest.getUrl();
		HttpBody httpBody = httpRequest.getBody();
		boolean hasParamUrlEncode = httpRequest.getConfig().hasParamUrlEncode();
		Map<String, ?> paramMap = beanToLinkedMap(httpBody);

		StringBuilder builder = url.getBuilder();
		if (!Eq.str("/", builder.charAt(builder.length() - 1))) {
			url.append("/");
		}

		IteratorUtils.entrySet(paramMap, (k, v) -> {
			if (ValidParam.isNotNull(v)) {
				String value = String.valueOf(v);
				if (hasParamUrlEncode) {
					url.append(StrEncodeUtils.urlEncode(value)).append("/");
				} else {
					url.append(value).append("/");
				}
			}
		});
		if (builder.length() > 0) {
			builder.deleteCharAt(builder.length() - 1);
		}
		httpBody.setRequestBody(null);
		httpRequest.setBody(httpBody);
		return httpRequest;
	}
}
